package serverx

import (
	"context"

	"gitee.com/workits/pkgs/casbinx"
	"gitee.com/workits/pkgs/contextx"
	"gitee.com/workits/pkgs/dbx"
	"gitee.com/workits/pkgs/errorx"
	"gitee.com/workits/pkgs/logx"
	"github.com/gin-gonic/gin"
)

// WithCasbin casbin中间件
func WithCasbin(cfg casbinx.Config) gin.HandlerFunc {
	// 初始化casbin模块
	casbinx.Enable(context.Background(), cfg, dbx.GetDefaultDao())
	return func(ctx *gin.Context) {
		// 执行验证
		if success, err := casbinx.Enforce(contextx.GetTraceUserRole(ctx.Request.Context()), ctx.Request.URL.Path, ctx.Request.Method); err == nil && success {
			ctx.Next()
		} else {
			if err != nil {
				logx.Errorf(err.Error(), ctx.Request.Context())
			}
			RenderError(ctx, errorx.ErrAPIForbidden)
		}
	}
}
